//
//  AppDelegate.swift
//  Exchange
//
//  Created by rui on 2018/4/16.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

import CoreTelephony.CTTelephonyNetworkInfo

import ZDCChat

import ZendeskSDK

import ZendeskCoreSDK



@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    var enterTime:Int64 = 0 //进入后台时间
    
    var isFirstRequest:Bool = false //标记网络请求
    
    //后台任务
    var backgroundTask:UIBackgroundTaskIdentifier! = nil
    
    func applicationInit() {
        NetworkMonitor.default.realNetworkMonitor.listener = { status in
            switch status {
            case .reachable:
                if self.isFirstRequest {
                    return
                }
                SocketManager.shared.subscribe(server: ServerExTick())
                AppContext.default.refreshLocalData()
                if APPTransactionPair.default.isRequestIng == false && APPTransactionPair.default.isRequestFail {
                //获取交易对
                APPTransactionPair.default.startPair()
                }
                if AppInfo.default.isLogin {
                    ChatWebScoket.manager.login()
                    AppSecurityInfo.default.archiveSecurityInfo()
                }
                NotificationCenter.default.post(name: NSNotification.Name.Exchange.RefreshBanner, object: nil)
                self.isFirstRequest = true
                break
            case .unknown:
                print("unknown")
            case .notReachable:
                print("notReachable")
            }

        }
        NetworkMonitor.default.realNetworkMonitor.startListening()
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        ZDCChat.initialize(withAccountKey: AppKey.zendeskKey)
        
//        ZDKZendesk
        Zendesk.initialize(appId: AppKey.zendeskAppId
            , clientId: AppKey.zendeskClientId
            , zendeskUrl: AppKey.zendeskAddress)
    
        Support.initialize(withZendesk: Zendesk.instance)
        let ident = Identity.createAnonymous()
        Zendesk.instance?.setIdentity(ident)
        
        
        
        Bundle.setLanguage(AppCacheInfo.default.language)
        if #available(iOS 10.0, *) {
            self.networkStatus(application, didFinishLaunchingWithOptions: launchOptions)
        }else {
            self.applicationInit()
        }
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.backgroundColor = UIColor.black
        window?.rootViewController = BaseTabBarViewController()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        AppSecurityInfo.default.readDic()
        if AppSecurityInfo.default.passWordDic[AppSecurityInfo.SecurityInfo.openScreenKey] == "1" {
            let time = Date().timeIntervalSince1970
            self.enterTime = Int64(time)
        }
        
        //如果已存在后台任务，先将其设为完成
        if self.backgroundTask != nil {
            application.endBackgroundTask(self.backgroundTask)
            self.backgroundTask = UIBackgroundTaskInvalid
        }
        
        //注册后台任务
        self.backgroundTask = application.beginBackgroundTask(expirationHandler: {
            () -> Void in
            //如果没有调用endBackgroundTask，时间耗尽时应用程序将被终止
            application.endBackgroundTask(self.backgroundTask)
            self.backgroundTask = UIBackgroundTaskInvalid
        })
        
       
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        AppSecurityInfo.default.readDic()
        if AppSecurityInfo.default.passWordDic[AppSecurityInfo.SecurityInfo.openScreenKey] == "1" {
            let time = Date().timeIntervalSince1970
            let nowTime = Int64(time)
            let lastTime = nowTime - self.enterTime
            if lastTime >= 600 {
                let controller:UIViewController =  CYMBShow.currentController()!
                let pop = ScreenLockerViewController()
                pop.style = .ScreenVerty
                controller.present(pop, animated: true, completion:  nil)
            }
        }
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func networkStatus(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey: Any]?) {
        ///模拟器
        if TARGET_IPHONE_SIMULATOR > 0 {
            self.applicationInit()
            return
        }
        //获取网络权限
        let cellularData = CTCellularData()
        cellularData.cellularDataRestrictionDidUpdateNotifier = {(state:CTCellularDataRestrictedState) in
            switch state {
            case .restrictedStateUnknown:
                self.applicationInit()
                break
            case .restricted:
                self.applicationInit()
                break
            case .notRestricted:
                self.applicationInit()
                break
            }
        }
        
    }
}

